<?php
declare (strict_types = 1);

namespace app\validate;

use think\Validate;

class WebsiteValidate extends Validate
{
    /**
     * 定义验证规则
     * 格式：'字段名' =>  ['规则1','规则2'...]
     *
     * @var array
     */
    protected $rule = [
        'id|网站ID' => 'require|number',
        'title|网站名称' => 'require|length:2,80',
        'parent_id|父站点ID' => 'require|number',
        'domain|网站域名' => 'require|unique:website|validateDomain',
    ];

    protected $scene = [
        'save' => ['title','domain','parent_id'],
        'update' => ['id','title','domain','parent_id'],
        'setStatus' => ['id','status'],
    ];

    // 验证域名格式
    protected function validateDomain($value)
    {
        // 正则表达式验证域名或 IP 地址加端口号
        $pattern = '/^(?:(?:https?|ftp):\/\/)?(?:\S+(?::\S*)?@)?(?:(?:(?:[a-z0-9]+(?:-[a-z0-9]+)*)\.)+[a-z]{2,}|(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(?::\d{2,5})?(?:\/[^\s]*)?$/i';
        return preg_match($pattern, $value) ? true : lang('域名格式错误');
    }
}
